package com.qin.service.impl;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.qin.dao.UserDao;
import com.qin.entity.Book;
import com.qin.entity.Order;
import com.qin.entity.OrderBook;
import com.qin.entity.User;
import com.qin.service.BookService;
import com.qin.service.OrderBookService;
import com.qin.service.OrderService;
import com.qin.service.UserService;

import cn.hutool.db.Session;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.log.StaticLog;

/**
 * 用户服务接口实现
 * @author BestRiven
 *
 */
public class UserServiceImpl implements UserService{

	private UserDao userDao = new UserDao();
	private OrderService orderService= new OrderServiceImpl();
	private OrderBookService orderBookService= new OrderBookServiceImpl();
	private BookService bookService= new BookServiceImpl();
	
	/**
	 * 添加用户
	 */
	@Override
	public Long insertUser(User user) {
		return userDao.insertUser(user);
	}


	@Override
	public int deleteUser(Long id) {
		return userDao.logincDeleteUser(id);
	}


	@Override
	public int updateUser(Long id, User user) {
		return userDao.updateUser(id, user);
	}


	@Override
	public User queryUser(Long id) {
		return userDao.queryUser(id);
	}


	@Override
	public List<User> queryAllUsers() {
		return userDao.querryAllUsers();
	}


	@Override
	public User queryUserByNameOrByEmail(String str, Boolean isEmail) {
		return userDao.queryUser(str, isEmail);
	}


	@Override
	public int paymentOrder(Long id, User user) {
		// 开启事务
		Session session = Session.create();
		// 准备一个List，用来存放发送图书的地址
		List<File> bookUrl = new ArrayList<>();
		// 准备拼装订单里面的信息
		StringBuffer orderBody = new StringBuffer();	
		
		int result = 0;
		try {
		    session.beginTransaction();
		    
		    // 先查询订单
		    Order queryOrderById = orderService.queryOrderById(id);
		    // 再查询用户
		    User queryUser = queryUser(user.getId());
		    // 判断订单的金额和用户的金额的大小
		    if(queryUser.getBalance() >= queryOrderById.getPrice()) {
		    	// 从新设置user账户的金额
		    	Double newBalance = queryUser.getBalance() -  queryOrderById.getPrice();
		    	String userSql = "UPDATE `user` SET `balance` = ? WHERE `id` = ?";
				session.execute(userSql, newBalance,user.getId());
				
		    	// 更新订单的信息，设置状态为true
				String orderSql = "UPDATE `order` SET `payment_status` = 1 WHERE `id` = ?";
				session.execute(orderSql, queryOrderById.getId());
				
		    	// 通过订单的信息，查到订单里面的图书信息
				List<OrderBook> queryOrdersBookByOrderId = orderBookService.queryOrdersBookByOrderId(queryOrderById.getId());
				// 遍历这个订单图书
				Iterator<OrderBook> iterator = queryOrdersBookByOrderId.iterator();
				while(iterator.hasNext()){
					// 拿到真正遍历的订单图书
					OrderBook orderBook = iterator.next();
					// 先拿到book的id
					Long bookId = orderBook.getBookId();
					// 再拿到数量
					Integer bookNum = orderBook.getBookNum();
					
					// 根据id查询图书的信息
					Book bookById = bookService.getBookById(bookId);
					
					// 开始拼接
					orderBody.append("<p>"+orderBook.getBookNum()+"本"+bookById.getTitle()+"</p>");
					
					// 判断库存是否足够
					if(bookById.getStock() < bookNum) {
						// 如果不够，则需要回滚然后返回值
						session.quietRollback();
						return 0;
					}
					
					// 开始批量修改（库存和销量）
					String bookSql = "UPDATE `book` SET `stock` = `stock`-?,`sales` = `sales`+?   WHERE `id` = ?";
					try {
						session.execute(bookSql, bookNum,bookNum,bookId);
					} catch (SQLException e) {
						e.printStackTrace();
					}
					// 把图书的url地址放入
					bookUrl.add(new File(bookById.getFileUrl()));
				}
				
				// 成功后，返回订单里订单图书的数量
				result = queryOrdersBookByOrderId.size();
		    }
		    // 订单大，返回失败 0
			// 插入订单没有问题了，再批量发送邮箱
			 MailUtil.send(queryUser.getEmail(), "小行星书城", getUserHtml(user,orderBody).toString(), true,bookUrl.toArray(new File[bookUrl.size()]));
			 StaticLog.debug("邮件发送成功！！");
			 
			 session.commit();
		    
		} catch (Exception e) {
			StaticLog.debug("支付订单已回滚");
		    session.quietRollback();
		}
		StaticLog.debug("支付订单已成功！！");
		
		return result;
	}
	
	public StringBuffer getUserHtml(User user,StringBuffer orderBody) {
		StringBuffer msg = new StringBuffer("<p>尊敬的"+user.getName()+",您好!</p>");
		msg.append("<p>您购买的:</p>");
		msg.append(orderBody);
		msg.append("<p>已到货,请在附件中查看</p>");
		StaticLog.debug("拼接的信息是：{}", msg);
		return msg;
	}

}
